package com.example.utils;

import org.junit.jupiter.api.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//权限过滤验验证器
@WebFilter(filterName = "AuthFilter", urlPatterns = "/*")
@Order(1)
public class AuthFilter implements Filter {
    private final String[] excludedUrls = {"/login","/json",".js",".css",".ico",".jpg",".png"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        //获取请求的URL
        String url = httpRequest.getRequestURI();

        //检查 URL 是否需要过滤
        boolean needFilter = true;
        for (String excludedUrl : excludedUrls) {
            if (url.contains(excludedUrl)) {
                needFilter = false;
                break;
            }
        }

        if (!needFilter) {
            // 不需要过滤的 URL，直接放行
            chain.doFilter(request, response);
        } else {
            Object user = httpRequest.getSession().getAttribute("user");
            //如果未登录，没有用户信息，则跳转到登录页面
            if (user == null) {
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
            } else {
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
